#include "kbd.h"


char scankbd()
{
	static char kbd_state = 0;
	unsigned char kbd_press;
	char kbd_return = 16;
	char row;

	switch(kbd_state)
	{
		case kbd_state_0:
			kbd_io=0x0f; P42=0; P44=0;
			kbd_press =kbd_io;
			
			if(kbd_press != kbd_maskrow)
				kbd_state = kbd_state_1;
			break;
			
		case kbd_state_1:
			kbd_press =kbd_io;
			if(kbd_press != kbd_maskrow){
				if((kbd_io&0x08)==0)  row=0;
				if((kbd_io&0x04)==0)  row=1;
				if((kbd_io&0x02)==0)  row=2;
				if((kbd_io&0x01)==0)  row=3;
				
				kbd_io=0xf0; P42=1;P44=1; //
				if(P44==0) kbd_return=row;
				if(P42==0) kbd_return=row+4;
				if((kbd_io&0x20)==0) kbd_return=row+8;
				if((kbd_io&0x10)==0) kbd_return=row+12;		
				kbd_state = kbd_state_2;
			}
			else
				kbd_state = kbd_state_0;
			break;
			
		case kbd_state_2:
			kbd_io=0x0f; P42=0; P44=0;
			kbd_press =kbd_io;
			if(kbd_press == 0x0f)	kbd_state = kbd_state_0;
			break;
		default:
			break;
	}
     
	return kbd_return;

}

